import wsgiref.handlers
import cgi
import os
import urllib
import webob
import Fetch
import Auth
import Mods
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import datastore
from google.appengine.api import datastore_types

class MainHandler(webapp.RequestHandler):

  def get(self):
    m = Mods.Mod()
    dsmm = Mods.DomSpecModMap()
    gmm = Mods.GlobalModMap()
    allMods = db.GqlQuery("SELECT * FROM Mod")
    singleMod = Mods.Mod()
    user = users.get_current_user()
    

        
        
    if user:
      
      if self.request.get("action") == "delete":
          mdmod = Mods.Mod()
          mdmod = db.GqlQuery("SELECT * FROM Mod WHERE name = :1", self.request.get("name"))
          if users.IsCurrentUserAdmin():
            mdmod.get().delete()
            self.response.out.write("""<html>
                                    <head>
                                                                <meta http-equiv="REFRESH" content="2;url=/interface/">
                                    </head>
                                    <body>
                                    Deleted.
                                    </body>
                                    </html>""")
          else:
            self.response.out.write("""<html>
                                    <head>
                                                                <meta http-equiv="REFRESH" content="2;url=/interface/">
                                    </head>
                                    <body>
                                    Sorry. You're not admin.
                                    </body>
                                    </html>""")
          
          return          
      if self.request.get("action") == "submit":
          
          m.community = self.request.get("community")
          m.name = self.request.get("name")
          m.description = self.request.get("description")

          m.user = user
          m.owner= user
          m.text = self.request.get("text")
          m.nation = self.request.get("nation")
          if not users.IsCurrentUserAdmin:
            m.ratified = False
          else:
            m.ratified = True
          
          m.put()
          
          self.response.out.write("""<html>
                                  <head>
                                                                <meta http-equiv="REFRESH" content="2;url=/interface/">
                                  </head>
                                  <body>
                                  Thank you for your submition...
                                  </body>
                                  </html>""")
          
          return
      if self.request.get("action") == "add":
        
        if self.request.get("isGlobal") == "true":
            ret = gmm.gql("WHERE user = :1", user)
            if ret.count() > 0:
                gmm = ret.get()
            else:
                gmm.user = user
            gmm.globalmodlist.append(self.request.get("name"))
            gmm.put()
            self.response.out.write("""<html>
                        <head>
                            <meta http-equiv="REFRESH" content="2;url=/interface/">
                        </head>
                        <body>
                        that mod is now loaded for you
                        </body>
                        </html>""")
            return
        else:
            
            ret = dsmm.gql("WHERE user = :1 AND currentURL = :2", user, self.request.get("currentURL"))
            if ret.count() > 0:
                dsmm = ret.get()
            else:
                dsmm.user = user
                dsmm.currentURL = self.request.get("currentURL") 
            
            dsmm.domSpecMods.append(self.request.get("name"))
            dsmm.put()
            self.response.out.write("""<html>
                        <head>
                            <meta http-equiv="REFRESH" content="2;url=/interface/">
                        </head>
                        <body>
                        That site specific mod is now loaded for you on 
                        </body>
                        </html>""")            
            return
          
      #!!!!!!!!! TO DO   a form for sumbitting and one for adding and a list of mods relevant to the current user  
      self.response.out.write(""" <html>
                              <head>
                              <title>Masher Nations</title>
                  <script type="text/javascript">
                  	var searchtim;
                  	var oneStr="1";
                  	scrollIt = function(elid) {

		}

		dynodeLoader = function(scriptid, scriptlocation){
		 var  d  =  document;  
		 var  s  =  d.createElement('SCRIPT');
		 var  h  =  d.getElementsByTagName('head')[0];  	

		 if (document.getElementById(scriptid)){
		 	var oldscript = document.getElementById(scriptid);
			h.removeChild(oldscript);
                }		 s.src  =  scriptlocation;  
		 s.id = scriptid;
		 s.type='text/javascript';  
		 h.appendChild(s);  
		 

		}	
		var YahooSearchQuerey ="";
		searchYahoo = function(YahooQuerey){
			if (!YahooQuerey){
				var YahooQuerey = YahooSearchQuerey
			}
			var YahooURLFirstSlice = "http://boss.yahooapis.com/ysearch/web/v1/";
			
			var YahooURLSecondSlice = "?appid=BNHwh1bIkY2ouLBT_8EnbojRqZT0nCyto1c-&format=json&callback=onYahooSearchResponse";
			
			var meat = escape(YahooQuerey);
			
			dynodeLoader("YahooSearchDynode",YahooURLFirstSlice + meat + YahooURLSecondSlice);	
		}

		trimtoendof = function(stringin){
		
		return stringin.substr(stringin.indexOf("#---") + 4);
		
		}

		TBrowsergoto = function(URLin) {
			document.getElementById("input").value=trimtoendof(URLin);
			var goform = document.getElementById("goForm");
			
			goform.submit();
		}
		
		onYahooSearchResponse = function(YahooSearchResponseObject){
			var YahooSearchResultsDiv = document.getElementById("YahooSearchResults");
			var YahooSearchResultsHTML = "";
			
			for (var n=0;n<=9;n++){
				YahooSearchResultsHTML = YahooSearchResultsHTML + "<h2><a onfocus='if (TTKeysOn == oneStr) {this.scrollIntoView();}' onclick='TBrowsergoto(this.href);' href='#---" + YahooSearchResponseObject.ysearchresponse.resultset_web[n].url + "'>"  + YahooSearchResponseObject.ysearchresponse.resultset_web[n].title + "</a></h2><p>" + YahooSearchResponseObject.ysearchresponse.resultset_web[n].abstract + "</p>";
			}
			
			YahooSearchResultsDiv.innerHTML = YahooSearchResultsHTML;
			if(TTKeysOn == "1"){
				lasttext = "";
				curtext ="search complete";

				readit();
			}
		}
		
		</script>

<style type="text/css">
/* GLOBAL ELEMENTS */

body {
	background: #eeeeee;
	font-family: Verdana, Tahoma, Arial;
	font-size: 1.2em;


}

.main_container {
  margin-left: 10%;
  padding-left: 2%;
    margin-right: 10%;
  padding-right: 2%;
  padding-top: 10px;
  margin-top: 10px;
  border: 20px solid #1122AA;
  background-image: url(http://www.talklets-secure.com/drip.gif);
  background-position: right top;
  background-repeat: no-repeat;

    
}
a {
	font-weight: bold;
	text-decoration: underline;
	color: #444474;
}
a:hover { color: white; background: black; text-decoration: none;}
label {
	font-weight: bold;
	line-height: 20px;
}
.clear { clear: both; }

/* LAYOUT */
#centred {
padding: 50px;
}
.subtle {
  font-size: 0.6em;
  color: #5555ee;
}
#subtle {
  font-size: 0.6em;
  color: #5555ee;
}


#YahooSearchResults {

	max-height:200px;
	overflow: auto;

}

#logo {
	width: 313px; height: 40px;

	float: right;
	padding: 5px;}
#footer {
	position: relative;
	clear: both;
	width: 100%;
	font-size: x-small;
	text-align: center;
	background: #dddddd;
	line-height: 20px;
}

#gbh {
top: -100px;
}

/* CONTENT STYLING */
select {
  
  border: solid red 1px;
  background: #fefecc;
  font-size: 1.5em;
  width: 50%;
        
        margin: 2%;  
}
h1 {

	font-size: 1.3em;
	color: #5577dd;

}
h1 span { color: #66CC33; }
hr { display: none; }
.hr {
	height: 1px;
	width: 100%;
	background: #CC3333;
	clear: both;
	margin: 10px 0 10px 0;
}
form {

	background: #eee;
}
.urlinput {
	width: 50%;
	border: 1px solid #CC3333;
	font-size: 150%;
	padding: 2px;
        
        margin: 2%;
}

.submitbutton {
	margin-left: 5px;
	height: 30px;
	padding: 0; text-align: center;
	font-weight: bold;
	border: 1px solid #CC3333;
}
#options { padding: 5px; }
#error { 
	color: #FF3333;
	border: 1px dotted #ccc;
	padding: 2px;
}

/* TOOLTIP HOVER EFFECT */
.tooltip { cursor: help; }
.tool-tip {
	color: #fff;
	width: 200px;
	z-index: 1000;
	background: #555;
	font-size: 85%;
}
.tool-title {
	font-weight: bold;
	margin: 0;
	padding: 4px;
}
.tool-text {
	padding: 0 6px 6px 6px;
}
</style>
<script type="text/javascript" src="includes/js/effects.js"></script>
<script type="text/javascript">
<!--
window.addEvent('domready', function() {
	optionsFx = new Fx.Slide('options');
	optionsFx.hide();
	new Tips($$('.tooltip'));
	$('input').focus();
});
//-->

</script>

<script src="http://s3.talklets-secure.com/Talklets2/jsLaunch.aspx" type="text/javascript"></script>

                             </head>
                              <body>
                              
<div class="main_container">


<h1> Masher Nations </h1>
<span class="subtle">
Hello, 
                              """ + user.nickname() + """
</span>
<p>
Welcome to your world. Make of it what you will.
</p>
<div id="theTTLinksId" style="background:white; borde: 1px solid #555555; margin:10px; width: 50%; padding:10px;">
     <!--TALKLETS FOR WEBSITES--><a href="javascript:" id="TTLaunchA"><img style="border: 0px none ;" src="http://217.199.191.202/images/198/usetalkletsbutton00.gif" alt="Text-to-speech screen reading accessibility. Click to listen to website." id="talkletslaunchbutton"/> </a><!-- copyright 2006 Textic Ltd. --><!--TALKLETS FOR WEBSITES-->          
    </div>

			<!-- CONTENT START -->
			
        <!--[glype:error]--><div>
                        
        </div>
        
	
		<form onsubmit="searchYahoo(); return false;">






		
<input class="urlinput" id="Yahoo_Querey_Search_Input" onkeyup="YahooSearchQuerey = this.value; clearTimeout(searchtim); searchtim = setTimeout('searchYahoo();',160);" type="textbox">
<label for="Yahoo_Querey_Search_Input"> Search</label>
		<input value="Submit Yahoo Powered Search Query" style="visibility: hidden;" type="submit">		



		</form>




		<div id="YahooSearchResults">
			
			
			
		</div>
	<br>
	<form id="goForm" action="../" method="get">

		<input name="" id="input" class="urlinput" size="40" type="text"><label for="input"> URL</label>
		<br><br><label><input id="go" value="proxy now" class="submitbutton" type="submit"> Submit</label>
		

		
	<div style="margin: 0px; overflow: hidden; height: 0px;"><div style="margin: -10px 0px 0px;" id="options">
                
                          
		</div></div></form>
                  
                         
			<!-- CONTENT END -->
			
                            
                              <h2>submit a mod</h2>
                              <form action="" method="POST">
                              <input type="text" class="urlinput" name="name" id="name"/><label FOR="name" >Name (of the Mod)</label><br>
                              <textarea type="text" class="urlinput" id ="description" name="description"></textarea><label FOR="description">Description</label><br>                              
                              <input type="text" class="urlinput" name="community" id="community"/><label FOR="community">Community</label><br>
                              <textarea type="text" class="urlinput" name="text" id="text"></textarea><label FOR="text">Text of the javascript mod</label><br>
                              <input type="text" class="urlinput" id="nation" name="nation"/><label FOR="nation">Nation.</label> This is the "Masher Nation" it should belong to. The Superclass of a community, if you like.<br>
                              <input type="HIDDEN" class="urlinput" name="action" value="submit"/><br>
                              <input type="submit" class="submitbutton" name="" value="subit a mod"/><br>
                              </form>
                              
                              <h2>Add a global mod to your preferances (one applied to all sites)</h2>
                              <form action="">
                              <select name="name" >""")
      desc = u""
      for singleMod in allMods:
        if singleMod.description:
          desc=singleMod.description
        self.response.out.write("""
                                <option value='""" + singleMod.name + """'>""" + singleMod.name + """ - """ + desc.encode('utf8') + """ </option> """)
      
      self.response.out.write("""
                              </select>
                              <input type="HIDDEN" name="action" value="add"/><br>
                              <input type="HIDDEN" name="isGlobal" value="true"/><br>
                              <input type="submit" name=""  class="submitbutton" value="add global mod"/><br>
                              </form>
                              <h2>Add a site specific mod to your preferances (one applied to the site you specify)</h2>
                              <form action="">
                              <select name="name" >""")
      
      for singleMod in allMods:
        if singleMod.description:
          desc=singleMod.description
        self.response.out.write("""
                                <option value='""" + singleMod.name + """'>""" + singleMod.name + """ - """ + desc.encode('utf8') + """</option> """)
      
      self.response.out.write("""
                              </select>
                              <input type="text"  class="urlinput" name="currentURL" id="currentURL"/><label FOR="currentURL">Domain </label>(e.g. www.foo.com) of the site you want it to be applied to<br>
                              <input type="HIDDEN" name="action" value="add"/><br>
                              <input type="HIDDEN" name="isGlobal" value="false"/><br>
                              <input type="submit" name=""  class="submitbutton" value="add a site specific mod"/><br>
                              </form>

                              """)
      
      self.response.out.write("""<h2>Global Mods</h2>
                                """)
      q = gmm.gql("WHERE user = :1", user)
      mgmm = Mods.GlobalModMap()
      
      if q.count() >=1:

        for mgmm in q:
          for item in mgmm.globalmodlist:
            
            
            self.response.out.write("<br>" + item)
        
      self.response.out.write("""<h2>Site specific Mods</h2>
                                """)
      req = dsmm.gql("WHERE user = :1", user)
      mdsmm = Mods.DomSpecModMap()
      if req.count() >= 1:
        for mdsmm in req:
          self.response.out.write("""<h3>""" + mdsmm.currentURL + """</h2>
                                <br>""")
          for item in mdsmm.domSpecMods:
            self.response.out.write("<br>" + item  + "<br>")
          
      self.response.out.write("""<h2>All available Mods</h2>""")
      self.response.out.write("""<ul>""")
      for singleMod in allMods:
        self.response.out.write("""<li>""" + singleMod.name + """
                                <a href='?action=delete&name=""" + singleMod.name + """' >Delete</a>
                                
                                """)
        
      self.response.out.write("""</l></div></html>
                                """)


        
        
      
    else:
      self.redirect(users.create_login_url(self.request.url))
  
  def post(self):
    MainHandler.get(self)




def main():
  application = webapp.WSGIApplication([('/interface/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()